<template>
    <div class="payment">
        <el-form :rules="rules" ref="form" :model="sceneInfo">
            <el-form-item prop="name">
                <div class="item">
                    <div class="label">场景名称：</div>
                    <div class="name" v-if="!(type==='add')">{{sceneInfo.name}}</div>
                    <div class="name" v-else>
                        <el-input maxlength="24" type="text" placeholder="场景名称" v-model.trim="sceneInfo.name"
                                  show-word-limit></el-input>
                    </div>
                </div>
            </el-form-item>
            <el-form-item prop="selectedFunc">
                <div class="item">
                    <div class="label">
                        功能选择：
                    </div>
                    <div class="funcList">
                        <p class="">默认支持3个功能，超出按每个 100元/功能 计费</p>
                        <div>
                            <el-checkbox-group class="check-group" v-model="sceneInfo.selectedFunc"
                                               @change="priceChange">
                                <el-checkbox class="check-box" v-for="func in funcList" :label="func.type"
                                             :value="func.type"
                                             :key="func.type">
                                    <div class="info">
                                        <div class="func-icon"><i :class="func.icon"></i></div>
                                        <div class="text">{{func.name}}</div>
                                        <div class="price">￥&nbsp;{{func.price}}</div>
                                        <div class="nig">
                                            <span @click.stop.prevent="">demo</span>
                                            <span @click.stop.prevent="">介绍</span>
                                        </div>
                                    </div>
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                </div>

            </el-form-item>
            <el-form-item prop="number">
                <div class="item">
                    <div class="label">参会人数：</div>
                    <div class="name people">
                        <el-slider v-model="sceneInfo.number" :max="2000"></el-slider>
                        <div class="maxNum">{{sceneInfo.number}}人</div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item prop="selectedTime">
                <div class="item">
                    <div class="label">使用期限：</div>
                    <div class="funcList">
                        <div>
                            <el-checkbox-group class="check-group" v-model="sceneInfo.selectedTime"
                                               @change="priceChange">
                                <el-checkbox class="check-box" v-for="time in timeList" :label="time.type"
                                             :value="time.type"
                                             :key="time.type">
                                    <div class="info">
                                        <div class="func-icon"><i :class="time.icon"></i></div>
                                        <div class="text">{{time.name}}({{time.day}}天)</div>
                                        <div class="price">￥{{time.price}}</div>
                                    </div>
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item prop="activeTime">
                <div class="item">
                    <div class="label">激活时间：</div>
                    <div class="name date">
                        <div class="picker">
                            <el-date-picker
                                    v-model="sceneInfo.activeTime"
                                    align="right" @change="acTimeChange"
                                    type="date" format
                                    placeholder="选择日期">
                            </el-date-picker>
                            &nbsp; &nbsp; ~ &nbsp; &nbsp;
                            <div>{{ new Date(sceneInfo.endTime).toLocaleDateString().replace(/\//g,'-')}}</div>
                            <el-date-picker disabled style="display: none"
                                            v-model="sceneInfo.endTime"
                                            align="right"
                                            type="date" format
                                            placeholder="选择日期">
                            </el-date-picker>
                        </div>
                        <div class="text">场景激活之前，场景只支持10个参会观众</div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item>
                <div class="item">
                    <div class="label">功能费用：</div>
                    <div class="name">
                        {{this.sceneInfo.selectedFunc.length-3>0?`( ${this.sceneInfo.selectedFunc.length} - 3 ) * 100 =￥
                        ${(this.sceneInfo.selectedFunc.length-3)*100}`:'￥ 0'}}
                    </div>
                </div>
            </el-form-item>
            <el-form-item>
                <div class="item">
                    <div class="label">资源使用费：</div>
                    <div class="name">
                        <!--{{`(${sceneInfo.number}-200) * 1(元/人)=￥${sceneInfo.number}`}}-->
                        {{this.sceneInfo.number-200>0?`( ${this.sceneInfo.number} -200 ) * 1 =
                        ￥${this.sceneInfo.number-200}`:'￥ 0'}}
                    </div>
                </div>
            </el-form-item>
            <el-form-item>
                <div class="item">
                    <div class="label">优惠码：</div>
                    <div class="name coupons">
                        <el-input type="text" v-model="coupons.code" @input="getCoupons"></el-input>
                        <el-button readonly :loading="searchLoading" type="text" style="color: #555"
                                   icon="el-icon-refresh-right">{{searchLoading?'正在查找':'查找'}}
                        </el-button>
                        <div v-if="coupons.amount>0">优惠金额：-￥{{coupons.amount}}</div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item>
                <div class="item">
                    <div class="label">实付金额：</div>
                    <div class="name amount">
                        <div>
                            ￥{{totalCount}}
                        </div>
                        <el-tooltip placement="top" :hide-after="3000">
                            <div style="width: 100px" slot="content">试用模式只支持10位观众试用，并且场景有效期为72小时</div>
                            <el-button v-if="type==='add'" type="primary" @click="saveSceneInfo(true)">开始试用</el-button>
                        </el-tooltip>
                    </div>
                </div>
            </el-form-item>
            <el-form-item>
                <div class="payWay">
                    <div v-for="(way,index) in payWays" :class="sceneInfo.payType===way.type?'active':''"
                         @click="payWayChange(index)">
                        <div>
                            <i :class="way.icon"></i>
                        </div>
                        <p>{{way.text}}</p>
                    </div>

                </div>
            </el-form-item>
            <div class="tip">
                <el-checkbox style="margin-right: 5px" v-model="isAgree"></el-checkbox>
                <span style="color: red">同意</span><a style="color: #1989FA" href="#">《智汇互动系统使用条款》</a>中的各项内容
            </div>
            <div class="buttons">
                <el-button type="info" @click="closePayment">取消</el-button>
                <el-button type="primary" @click="saveSceneInfo(false)">立即开通</el-button>
            </div>
        </el-form>

        <el-dialog :visible.async="codeImgVisible" width="350px" center :title="sceneInfo.payType===0?'扫码支付':'支付'"
                   @close="codeImgVisible=false" append-to-body :z-index="100">
            <div v-if="sceneInfo.payType===0">
                <div id="qrCode" style="text-align: center;display: flex;justify-content: center"></div>
                <div style="text-align: center;margin-top: 20px">
                    <el-button @click="codeImgVisible=false">关闭</el-button>
                </div>
            </div>
        </el-dialog>
        <el-dialog :custom-class="'bank definedModal'" title="银行转账" width="650px" :visible="bankModel"
                   @close="closeBankModal"
                   append-to-body v-if="bankModel">
            <el-form ref="bankForm" :model="bankInfo" :rules="bankInfo.rules">
                <div class="bank-info can-select">1.&nbsp;汇款验证码：<a>{{bankInfo.tradeNum}}</a>，请将汇款识别码填写在电汇凭证的“汇款用途”栏目中
                </div>
                <div class="bank-info can-select">2.&nbsp;请将活动实付金额转账至开心大屏幕官方银行卡</div>
                <div class="bank-info can-select">户名：上海XX科技有限公司&nbsp;&nbsp;&nbsp;银行卡号：<span
                        style="padding: 0 10px;text-decoration: underline">31050170380000001250</span></div>
                <div class="bank-info can-select">开户地址：中国建设银行股份有限公司上海浙江路支行</div>
                <el-form-item label-width="130px" label="订单号："><a class="can-select">{{bankInfo.tradeNum}}</a>
                </el-form-item>
                <el-form-item label-width="130px" label="转款用户名：" prop="userName">
                    <el-input type="text" v-model="bankInfo.userName"></el-input>
                </el-form-item>
                <el-form-item label-width="130px" label="联系人手机号：" prop="tel">
                    <el-input type="text" v-model="bankInfo.tel"></el-input>
                </el-form-item>
                <el-form-item label-width="130px" label="转款账号：" prop="cardNum">
                    <el-input type="text" v-model="bankInfo.cardNum"></el-input>
                </el-form-item>
                <div style="text-align: center;padding-top: 20px">
                    <el-button style="width: 150px" type="primary" @click="bankSubmit">提交</el-button>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    import QRCode from 'qrcodejs2';

    export default {
        name: 'payment',
        props: {
            type: {
                required: true,
            },
            closePayment: {
                required: true,
                type: Function,
            },
            getSceneList: {},
        },
        data() {
            return {
                modelVisible: false,
                codeImgVisible: false,
                bankModel: false,
                funcList: [],
                timeList: [],
                payWays: [
                    { icon: 'el-icon-warning', text: '微信', type: 0 },
                    { icon: 'el-icon-warning', text: '支付宝', type: 1 },
                    { icon: 'el-icon-warning', text: '银行转账', type: 2 },
                ],
                sceneInfo: {
                    name: '', number: 200, selectedFunc: [], selectedTime: [],
                    activeTime: '', endTime: +new Date(), payType: 0,
                },
                bankInfo: {
                    cardNum: '',
                    tradeNum: '',
                    userName: '',
                    tel: '',
                    rules: {
                        cardNum: [
                            { required: true, message: '请输入您的汇款账号', trigger: 'blur' },
                        ],
                        userName: [
                            { required: true, message: '请输入用户名', trigger: 'blur' },
                        ],
                        tel: [
                            { required: true, message: '请输入手机号码', trigger: 'blur' },
                            { pattern: /^[1][345678][0-9]{9}$/, message: '手机号格式不正确', trigger: 'change' },
                        ],
                    },
                },
                isAgree: true,
                searchLoading: false,
                coupons: { amount: 0 },
                rules: {
                    name: [
                        { required: true, message: '请输入场景名称', trigger: 'blur' },
                    ],
                    selectedFunc: [
                        { required: true, message: '请至少选择一个功能', trigger: 'change' },
                    ],
                    selectedTime: [
                        { required: true, message: '请选择使用期限', trigger: 'change' },
                    ],
                    number: [],
                    activeTime: [
                        { required: true, message: '请选择激活日期', trigger: 'blur' },
                    ],
                },
            };
        },
        computed: {
            totalCount() {
                let info = this.sceneInfo;
                let module_price = this.sceneInfo.selectedFunc.length - 3 > 0 ? (this.sceneInfo.selectedFunc.length - 3) * 100 : 0;
                let useDatePrice = this.sceneInfo.selectedTime.length > 0 ? this.getSelectedInfo('time', this.sceneInfo.selectedTime[0]).price : 0;
                let personPrice = info.number > 200 ? info.number - 200 : 0;
                // console.log(module_price,useDatePrice,personPrice,this.sceneInfo.selectedTime)
                let totalPrice = parseInt(module_price) + parseInt(useDatePrice) + parseInt(personPrice);
                let cutPrice = this.coupons.amount;
                // console.log(module_price, useDatePrice, personPrice, totalPrice, cutPrice);
                return totalPrice - cutPrice;
            },
        },
        mounted() {
            if (this.type !== 'add') {
                this.setSceneInfo(this.type);
            }
            let list = sessionStorage.getItem('tc');
            if (list) {
                let { funcList, timeList } = JSON.parse(list);
                this.funcList = funcList;
                this.timeList = timeList;
            } else {
                this.$api.get('/data/module_time', null, success => {
                    // console.log(success);
                    sessionStorage.setItem('tc', JSON.stringify(success));
                    this.funcList = success.funcList;
                    this.timeList = success.timeList;
                }, fal => {
                    this.$message.error(fal);
                });
            }

            // this.showQRcode('https://www.baodu.com');

        },
        methods: {
            priceChange() {
                this.sceneInfo.selectedTime.length > 1 ? this.sceneInfo.selectedTime = [this.sceneInfo.selectedTime[1]] : null;
                this.acTimeChange();
                // console.log(this.sceneInfo.selectedFunc, this.selectedTime);
            },
            acTimeChange() {
                // console.log(this.sceneInfo.activeTime, this.sceneInfo.endTime, this.sceneInfo.selectedTime);
                let startTime = Date.parse(this.sceneInfo.activeTime), endTime = Date.parse(this.sceneInfo.endTime);
                if ((!startTime && !endTime) || startTime <= endTime) {
                    this.sceneInfo.activeTime = '';
                    this.sceneInfo.endTime = +new Date();
                    // console.log(this.sceneInfo.endTime);
                } else {
                    if (this.sceneInfo.selectedTime[0]) {
                        let time = this.getSelectedInfo('time', this.sceneInfo.selectedTime[0]);
                        this.sceneInfo.endTime = startTime + time.day * 24 * 3600 * 1000;
                    }
                }
            },
            getCoupons() {
                if (window.searchTimer) {
                    clearInterval(window.searchTimer);
                }
                this.searchLoading = true;
                if (this.coupons.code.length > 1) {
                    window.searchTimer = setTimeout(() => {
                        this.coupons.amount = parseInt(100 * Math.random());
                        this.searchLoading = false;
                    }, 500);
                }
            },
            payWayChange(index) {
                if (index === 2) {
                    this.saveSceneInfo();
                }
                this.sceneInfo.payType = this.payWays[index].type;
            },
            saveSceneInfo(isTrial) {
                // console.log('shiyong',isTrial)
                if (!this.isAgree) {
                    this.$message.info('请阅读《智汇互动系统使用条款》，并选择同意此条款');
                    return false;
                }
                let is_trial = isTrial;
                this.$refs.form.validate(res => {
                    if (res) {
                        let info = this.sceneInfo;
                        let moduleJson = [];
                        this.sceneInfo.selectedFunc.forEach(item => {
                            moduleJson.push(this.getSelectedInfo('func', item));
                        });
                        let module_price = this.sceneInfo.selectedFunc.length - 3 > 0 ? (this.sceneInfo.selectedFunc.length - 3) * 100 : 0;
                        let useDatePrice = this.sceneInfo.selectedTime.length > 0 ? this.getSelectedInfo('time', this.sceneInfo.selectedTime[0]).price : 0;
                        let personPrice = info.number > 200 ? info.number - 200 : 0;
                        let totalPrice = parseInt(module_price) + parseInt(useDatePrice) + parseInt(personPrice);
                        let cutPrice = this.coupons.amount;
                        let finalPrice = totalPrice - cutPrice;
                        // console.log(info.endTime,Date.parse(info.endTime))
                        let param = {
                            name: info.name,
                            moduleJson,
                            module_price,
                            maxPerson: info.number,
                            personPrice,
                            useStartDate: Date.parse(info.activeTime),
                            useEndDate: info.endTime,
                            useDatePrice,
                            totalPrice,
                            cutPrice,
                            finalPrice: finalPrice,
                            payType: info.payType,
                            bankPayDetail: [],
                            test: is_trial,
                            dateType: info.selectedTime[0],
                        };
                        this.$api.post('/st_scene/create', param, success => {
                            if (isTrial) {
                                this.$message.success('试用成功(试用场景最多支持10位观众试用，使用时间为72小时)');
                                this.closePayment();
                                this.getSceneList();
                            } else {
                                switch (info.payType) {
                                    case 0:
                                        this.$api.get('/pay/wxpay/nativetest', { out_trade_no: success }, success => {
                                            this.codeImgVisible = true;
                                            this.showQRcode(success);
                                        }, fal => {
                                            this.$message.error('支付失败');
                                        });
                                        break;
                                    case 1:
                                        this.$api.get('/pay/alipay/webtest', { out_trade_no: success }, success => {
                                            let div = document.createElement('div');
                                            div.innerHTML = success;
                                            document.body.appendChild(div);
                                            div.getElementsByTagName('form')[0].submit();
                                        }, fal => {
                                            this.$message.error('支付失败');
                                        });
                                        break;
                                    case 2:
                                        this.bankInfo.tradeNum = success;
                                        this.bankModel = true;
                                        break;
                                }

                            }

                        }, fal => {
                            this.$message.error(fal);
                        });

                    }
                    else {
                        this.$message.info('请完善场景信息');
                        return false;
                    }
                });

            },
            getSceneInfo(sceneId) {
                let info;
                let sceneList = JSON.parse(sessionStorage.getItem('sceneList'));
                sceneList.forEach(item => {
                    if (item.sceneId === sceneId) {
                        info = item;
                    }
                });
                return info;
            },
            setSceneInfo(sceneId) {
                let info = this.getSceneInfo(sceneId);
                console.log('scene', info);
                let func = JSON.parse(info.moduleId);
                let selectedFunc = [];
                if (func instanceof Array) {
                    func.forEach(item => {
                        item ? selectedFunc.push(item.type) : null;
                    });
                }
                this.sceneInfo = {
                    name: info.name,
                    number: info.maxPerson,
                    activeTime: info.useStartDate ? info.useStartDate : '',
                    endTime: info.useEndDate ? info.useEndDate : +new Date(),
                    payType: 0,
                    selectedFunc,
                    selectedTime: info.sceneOrder.dateType ? [info.sceneOrder.dateType] : [],
                };
            },
            getSelectedInfo(type, id) {
                let info = '';
                if (type === 'func') {
                    this.funcList.forEach(item => {
                        item.type === id ? info = item : 0;
                    });
                } else {
                    this.timeList.forEach(item => {
                        item.type === id ? info = item : 0;
                    });

                }
                return info;
            },
            showQRcode(text) {
                setTimeout(() => {
                    let qrcode = new QRCode(document.getElementById('qrCode'), {
                        width: 200,
                        height: 200, // 高度
                        text,  // 二维码内容
                        render: 'canvas',  // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
                    }, 100);
                });
            },
            bankSubmit() {
                let info=this.bankInfo;
                this.$refs.bankForm.validate((res) => {
                    let bankPayDetail = {
                        cardNum:info.cardNum,
                        userName:info.userName,
                        tel:info.tel
                    };
                    this.$api.post('/st_scene/updateBank', {bankPayDetail, orderNo:info.tradeNum}, success => {
                        this.$alert('<div style="margin: 20px">请联系管理人员开通场景，电话：<span style="user-select: text;">2034-65789</span></div>', '提示', {
                            confirmButtonText: '确定',
                            dangerouslyUseHTMLString: true,
                        });
                        this.closePayment(1);
                    }, fal => {
                        this.$message.error(fal)
                    });

                });
            },
            closeBankModal() {
                this.sceneInfo.payType = 0;
                this.bankModel = false;
            },
        },
    };
</script>

<style lang="scss">
    .payment {
        .item {
            margin: 10px 0;
            display: flex;
            .label {
                margin-right: 10px;
                width: 100px
            }
            .name {
                width: calc(100% - 110px);
            }

        }

        .funcList {
            width: calc(100% - 110px);
            p {
                color: #999999;
            }
            & > div {
                display: flex;
                justify-content: flex-start;
                flex-wrap: wrap;
            }
        }

        .people {
            position: relative;
            & > div:first-of-type {
                margin-right: 6em;
            }
            .maxNum {
                width: 6em;
                text-align: center;
                position: absolute;
                top: 5px;
                right: 0;
            }
        }

        .date {
            .picker {
                display: flex;
            }
            .text {
                font-size: 12px;
                color: #999;
            }
        }

        .coupons {
            display: flex;
            align-items: center;
            div {
                width: 150px;
            }
            button {
                margin: 0 20px 0 5px;
                transition: all .3s;
            }
        }

        .info {
            width: 100%;
            height: 100%;
            position: relative;
            overflow: hidden;
            div {
                text-align: center;
                margin: 10px 0;
                font-size: 16px;
            }
            .text, .price {
                height: 20px;
            }
            .func-icon {
                margin-top: 16px;
                font-size: 34px;
                height: 34px;
            }
            .nig {
                margin: 0;
                position: absolute;
                left: 0;
                bottom: -130px;
                width: 100%;
                background: #555;
                color: #FFFFFF;
                padding: 10px;
                transition: all .3s;
                display: flex;
                span {
                    width: 50%;
                    padding: 0 6px;
                    font-size: 12px;
                }
                span:hover {
                    color: #1989FA;
                }
                span:first-of-type {
                    border-right: 2px solid #eeeeee;
                }
            }
            &:hover {
                .nig {
                    bottom: 0;
                }
            }
        }

        .amount {
            @include flex-bt;
            padding: 0 20px 0 10px;
        }

        .payWay {
            display: flex;
            justify-content: center;
            align-items: center;
            & > div {
                cursor: pointer;
                margin: 0 20px;
                @include container-border;
                border-radius: 5px;
                width: 100px;
                padding: 10px;
                transition: all 0.3s;
                div, p {
                    text-align: center;
                }
            }
            & > div:hover {
                border-color: #1989FA;
                transform: scale(1.2);
            }
            div.active {
                border-color: #1989FA;
                background: #c0eee8;
            }
        }

        .tip {
            text-align: center;
            padding: 10px;
        }

        .buttons {
            text-align: center;
            padding: 20px;
            button {
                width: 100px;
            }
        }
    }

    .bank {
        @include container-border;
        border-radius: 10px;

        .bank-info {
            padding: 10px 20px;
            font-size: 16px;
        }

    }

    .can-select {
        user-select: text;
    }
</style>